package com.itchen.headline.controller;

import com.itchen.headline.common.Result;
import com.itchen.headline.pojo.NewsType;
import com.itchen.headline.pojo.vo.HeadlineDetailVo;
import com.itchen.headline.pojo.vo.HeadlineQueryVo;
import com.itchen.headline.service.NewsHeadlineService;
import com.itchen.headline.service.NewsTypeService;
import com.itchen.headline.service.impl.NewsHeadlineServiceImpl;
import com.itchen.headline.service.impl.NewsTypeServiceImpl;
import com.itchen.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 一些基础不需要拦截器的功能，访问并发高，需要集群部署
 */

@WebServlet("/portal/*")
public class PortalController extends BaseController{
    private NewsTypeService newsTypeService = new NewsTypeServiceImpl();
    private NewsHeadlineService headlineService = new NewsHeadlineServiceImpl();

    /**
     * 查询头条详情
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showHeadlineDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收需要查询的hid
        int hid = Integer.parseInt(req.getParameter("hid"));
        // 调用服务层完成查询处理
        HeadlineDetailVo headlineDetailVo = headlineService.findHeadlineDetail(hid);
        // 将查询到的信息响应给客户端
        Map data = new HashMap();
        data.put("headline",headlineDetailVo);
        WebUtil.writeJson(resp,Result.ok(data));
    }

    /**
     * 查询所有头条类型
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findAllTypes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询所有的新闻
        List<NewsType> newsTypeList = newsTypeService.findAll();

        WebUtil.writeJson(resp,Result.ok(newsTypeList));
    }

    /**
     * 分页查询逻辑
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findNewsPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收请求类型的参数
        HeadlineQueryVo headlineQueryVo = WebUtil.readJson(req, HeadlineQueryVo.class);
        // 将参数传递 进行查询
        Map pageInfo = headlineService.findPage(headlineQueryVo);
        Map data = new HashMap();
        data.put("pageInfo",pageInfo);
        // 将查询结果返回并响应给客户端
        WebUtil.writeJson(resp,Result.ok(data));
    }
}
